import _ from 'lodash';

/**
 * @desc 初始化表格列
 * @param column_data 列表初始数据
 * @param is_check_select_auth 是否进行勾选的权限控制
 * @param select_rule 勾选的权限控制
 * @return {[]}
 */
function handleColumnData(_this, column_data, is_check_select_auth, select_rule) {
    let result = [];

    if (!_.isEmpty(column_data)){
        let selection = {};
        let select_index = _.findIndex(column_data, {type: 'selection'});

        // 构造表格列数据
        result = column_data.map(item => {
            let new_item = Object.assign({}, item)
            // 构造新标签页打开
            if (new_item.isLink && new_item.openUrl){
                new_item['render'] = (h, row) => {
                    return h(
                        'div',
                        {
                            class: 'table-title',
                            on: {
                                click() {
                                    let routeData = _this.$router.resolve({ name: new_item.openUrl, params: { id: row.id } });
                                    window.open(routeData.href, '_blank');
                                }
                            }
                        },
                        [
                            h('span', { class: 'v-link' }, row[new_item.prop])
                        ]
                    );
                };

                delete new_item.isLink;
                delete new_item.openUrl;
            }
            return new_item;
        });

        // 构造勾选权限
        if (is_check_select_auth && select_index != -1){
            column_data[select_index]['renderSelectable'] = (row) => {
                // 如果勾选规则非空，进行权限处理
                if (is_check_select_auth && select_rule){
                    let is_valid = true;

                    for (let key in select_rule){
                        is_valid = is_valid && row[key] === select_rule[key];
                    }

                    return is_valid;

                } else {
                    return true;
                }
            };
        } else if (is_check_select_auth && select_index == -1){
            selection = { label: '', type: 'selection', width: 80,
                renderSelectable: (row) => {
                    if (is_check_select_auth && select_rule){
                        let is_valid = true;

                        for (let key in select_rule){
                            is_valid = is_valid && row[key] === select_rule[key];
                        }

                        return is_valid;

                    } else {
                        return true;
                    }
                }
            };
        }

        result = !_.isEmpty(selection) ? [selection, ...result] : result;
    }

    return result;
}

export {
    handleColumnData
}